const { v4 } = require("uuid");
const { Result } = require("@/libs/result");
const arrayUtil = require("@/utils/array.util");
const dateUtil = require("@/utils/date.util");
const dbTableNameConstant = require("@/constants/db-table-name.constant");
const CommonService = require("@/common/common.service");
const productModel = require("./product.model");
const fileBusinessService = require("@/common/file-business.service");

/**
 * 产品服务
 * @author Haor
 * @created 2025/2/18
 */
class ProductService {
	commonService = new CommonService();

	/**
	 * 查询商品列表失败
	 * @param {*} param0
	 * @returns
	 */
	async queryProductList({ keyword, category_id, page, page_size }) {
		try {
			const result = await productModel.queryProductList({
				keyword: keyword || "",
				category_id: category_id || "",
				page: page || 1,
				page_size
			});
			if (result.code === 200) {
				let productList = result.results || [];
				// 设置每一条中图片
				await fileBusinessService.setBusinessRowsFile({
					rows: productList,
					businessIdFiled: "image_id",
					fileKey: "images"
				});
				productList = await this.commonService.setListRowUser({ list: productList }); // 设置列表行用户
				// 查询总条数
				const totalResult = await productModel.getProductTotal({
					keyword: keyword || "",
					category_id: category_id || ""
				});
				if (totalResult.code === 200) {
					const total = totalResult.results[0].count;
					return Result.Paging(Number(page), total, productList);
				}
				return Result.Failed("查询列表失败");
			}
			return Result.Failed("查询列表失败");
		} catch (error) {
			console.log(error);
			return Result.Failed("查询列表失败");
		}
	}

	async getProduct({ id }) {
        try {
            const [error, data] = await productModel.getProduct(id);
            if (error) {
                return Result.Failed("获取商品失败");
            }
            if (data.image_id) {
                const images = await fileBusinessService.getBusinessFiles(data.image_id, true);
                data.images = images;
            }
            return Result.Success(data);
        } catch (error) {
			return Result.Failed("获取商品失败");
		}
	}

	// 删除产品
	async deleteProduct({ id }, { tid, user }) {
		const [error] = await productModel.deleteProduct({ id: id  });
		if (error) {
			return Result.Failed("产品删除失败");
		}
		return Result.Success();
	}
	/**
	 * 创建产品
	 * @param {*} body
	 * @returns
	 */
	async createProduct(body) {
		try {
			const checkProductResult = await productModel.getProductByName({
				name: body.name
			});

			// 名称是否重复
			if (checkProductResult.code === 200 && checkProductResult.results.length > 0) {
				return Result.Failed("商品名称已存在");
			}

			let fileBusinessId = null;

			if (body.images && body.images.length > 0) {
				fileBusinessId = v4().toUpperCase();
			}

			// 创建产品
			const [error, data] = await productModel.createProduct({
				category_id: body.category_id,
				name: body.name,
				barcode: body.barcode,
				spec: body.spec || null,
				unit_id: body.unit_id || null,
				code: body.code,
				price: body.price || 0,
				cost_price: body.cost_price || 0,
				min_stock: body.min_stock || null,
				image_id: fileBusinessId || null
			});
			if (error) {
				return Result.Failed("创建产品失败");
			}

			await this.commonService.setRowLocked("product_unit", [...body.unit_id]); // 锁
			await this.commonService.setRowLocked("product_category", body.category_id); // 锁

			// 绑定附件
			if (fileBusinessId) {
				const [error] = await fileBusinessService.bindingFiles({
					business_id: fileBusinessId,
					files: body.images || [],
					business_type: "product.product_image"
				});
				if (error) {
					console.log("创建商品失败");
					return Result.Failed("创建产品失败");
				}
				await this.commonService.setRowLocked("file_files", [...body.images]); // 锁
			}

			return Result.Success(data);
		} catch (error) {
			console.log("创建产品失败：", error);
			return Result.Failed("创建产品失败");
		}
	}
	/**
	 * 修改产品
	 * @param {*} body
	 * @returns
	 */
    async updateProduct({ id }, body) {
        try {
			const [_error, product] = await productModel.getProduct(id);
            if (_error) {
                return Result.Failed("商品修改失败");
            }

            // 处理商品文件
            const fileBusinessId = product.image_id || v4().toUpperCase();

            // 创建产品
            const [error, data] = await productModel.updateProduct({
                id: id,
                data: {
                    category_id: body.category_id,
                    name: body.name,
                    barcode: body.barcode,
                    spec: body.spec || null,
                    unit_id: body.unit_id || null,
                    code: body.code,
                    price: body.price || 0,
                    cost_price: body.cost_price || 0,
                    min_stock: body.min_stock || null,
                    image_id: fileBusinessId || null
                }
			});
			if (error) {
				return Result.Failed("修改产品");
			}
            const result = await fileBusinessService.updateBusinessFiles({
                business_id: fileBusinessId,
                files: body.images || [],
                business_type: 'product.product_image'
            });
            if (!result) {
                console.log('商品修改图片错误！');
                return Result.Failed("商品修改失败");
            }
            await this.commonService.setRowLocked("file_files", [...body.images]); // 锁
			await this.commonService.setRowLocked("product_unit", [...body.unit_id]); // 锁
			await this.commonService.setRowLocked("product_category", body.category_id); // 锁
			return Result.Success(data);
		} catch (error) {
			console.log("修改商品失败", error);
			return Result.Failed("修改商品失败");
		}
	}
	/**
	 * 创建产品类别
	 * @param {*} body
	 * @returns
	 */
	async createProductCategory(body) {
		try {
			const [error, data] = await productModel.createProductCategory({
				name: body.name,
				code: body.code,
				sort: body.sort_order || 0,
				description: body.description || null
			});
			if (error) {
				return Result.Failed("创建产品类别失败");
			}
			return Result.Success(data);
		} catch (error) {
			console.log("创建产品失败：", error);
			return Result.Failed(error);
		}
	}

	/**
	 * 获取单个商品单位
	 * @param {*} data
	 * @returns
	 */
	async getProductCategory({ id }, data) {
		try {
			const [error, result] = await productModel.getProductCategory(id);
			if (error) {
				return Result.Failed("获取类别失败");
			}
			return Result.Success(result);
		} catch (error) {
			console.log(error.message);
			return Result.Failed("修改类别失败");
		}
	}

	/**
	 * 获取产品类别列表
	 */
	async queryProductCategoryList({}) {
		try {
			const data = await productModel.queryProductCategoryList();
			if (data.code === 200) {
				const results = await this.commonService.setListRowUser({ list: data.results }); // 设置列表行用户
				return Result.Success(results);
			}
			return Result.Failed("查询产品类别失败");
		} catch (error) {
			console.log("查询产品类别失败:", error);
			return Result.Failed("查询产品类别失败");
		}
	}

	/**
	 * 修改商品类别
	 * @param {*} data
	 * @returns
	 */
	async updateProductCategory({ id }, data) {
		try {
			const [error, result] = await productModel.updateProductCategory(id, {
				name: data.name,
				description: data.description || null
			});
			if (error) {
				return Result.Failed("修改类别失败");
			}
			return Result.Success(result);
		} catch (error) {
			console.log(error.message);
			return Result.Failed("修改类别失败");
		}
	}

	/**
	 * 删除商品类别
	 * @param {*} data
	 * @returns
	 */
	async deleteProductCategory({ id }) {
		try {
			const [error] = await productModel.deleteProductCategory(id);
			if (error) {
				return Result.Failed("删除类别失败");
			}
			return Result.Success();
		} catch (error) {
			console.log(error.message);
			return Result.Failed("删除类别失败");
		}
	}

	/**
	 * 创建商品单位
	 * @param {*} data
	 * @returns
	 */
	async createProductUnit(data) {
		try {
			if (!data.name) {
				return Result.Failed("创建商品单位失败");
			}
			const [error, result] = await productModel.createProductUnit({
				name: data.name,
				remark: data.remark || null
			});
			if (error) {
				return Result.Failed("创建商品单位失败");
			}
			return Result.Success(result);
		} catch (error) {
			console.log(error.message);
			return Result.Failed("创建商品单位失败");
		}
	}

	/**
	 * 创建商品单位
	 * @param {*} data
	 * @returns
	 */
	async updateProductUnit({ id }, data) {
		try {
			if (!data.name) {
				return Result.Failed("修改商品单位失败");
			}
			const [error, result] = await productModel.updateProductUnit(id, {
				name: data.name,
				remark: data.remark || null
			});
			if (error) {
				return Result.Failed("修改商品单位失败");
			}
			return Result.Success(result);
		} catch (error) {
			console.log(error.message);
			return Result.Failed("修改商品单位失败");
		}
	}

	/**
	 * 删除商品单位
	 * @param {*} data
	 * @returns
	 */
	async deleteProductUnit({ id }) {
		try {
			const [error] = await productModel.deleteProductUnit(id);
			if (error) {
				return Result.Failed("删除单位失败");
			}
			return Result.Success();
		} catch (error) {
			console.log(error.message);
			return Result.Failed("删除单位失败");
		}
	}

	/**
	 * 获取单个商品单位
	 * @param {*} data
	 * @returns
	 */
	async getProductUnit({ id }, data) {
		try {
			const [error, result] = await productModel.getProductUnit(id, {
				name: data.name,
				remark: data.remark || null
			});
			if (error) {
				return Result.Failed("获取商品单位失败");
			}
			return Result.Success(result);
		} catch (error) {
			console.log(error.message);
			return Result.Failed("修改商品单位失败");
		}
	}

	/**
	 * 查询商品单位
	 * @param {*} data
	 * @returns
	 */
	async queryProductUnitList(data) {
		try {
			const result = await productModel.queryProductUnitList();
			if (result.code !== 200) {
				return Result.Failed("查询商品单位失败");
			}
			return Result.Success(result.results || []);
		} catch (error) {
			console.log(error.message);
			return Result.Failed("查询商品单位失败");
		}
	}
}

module.exports = new ProductService();
